package com.frikinet.lifeguard.gui;

import static ch.lambdaj.Lambda.having;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.Lambda.select;

import java.awt.BorderLayout;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JPanel;

import org.lobobrowser.html.HtmlRendererContext;
import org.w3c.dom.html2.HTMLElement;
import org.w3c.dom.html2.HTMLLinkElement;

import ch.lambdaj.function.matcher.Predicate;

import com.frikinet.lifeguard.App;
import com.frikinet.lifeguard.events.MonthSelectedListener;
import com.frikinet.lifeguard.events.PostSelectedEvent;
import com.frikinet.lifeguard.events.YearMonthSelectedEvent;
import com.frikinet.lifeguard.model.Post;
import com.frikinet.lifeguard.util.Day;
import com.frikinet.lifeguard.util.HibernateUtil;
import com.frikinet.lifeguard.util.Month;
import com.frikinet.lifeguard.util.WeekNames;

public class MonthHtmlPanel extends JPanel implements MonthSelectedListener
{
	private static final long serialVersionUID = 1L;
	
	private TemplateHtmlPanel htmlPanel;
	
	public MonthHtmlPanel()
	{
		super(new BorderLayout());
		
		App.events.addMonthSelectedListener(this);
		
		buildGUI();
	}
	
	private void buildGUI()
	{
		htmlPanel = new TemplateHtmlPanel(new PostLinkBehaviour());
		add(htmlPanel, BorderLayout.CENTER);
	}
	
	@Override
	public void monthSelected(YearMonthSelectedEvent event)
	{
		Map<String, Object> context = new HashMap<String, Object>();
		
		String month = String.format("%d%02d", event.getYear(), event.getMonth());
		Map<String, Post> posts = new HashMap<String, Post>();
		for(Post post: select(event.getUser().getPosts(), having(on(Post.class).getDate(), new IsMonth(month))))
		{
			posts.put(Day.DAY_ID_FORMAT.format(post.getDate()), post);
		}
		context.put("posts", posts);

		context.put("weekDays", new WeekNames("EEEE"));
		
		context.put("month", new Month(event.getYear(), event.getMonth()));
		
		htmlPanel.navigate("month", context);
	}
	
	public static class IsMonth extends Predicate<Date>
	{
		private static SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		private String compare;
		public IsMonth(String compare)
		{
			this.compare = compare;
		}
		@Override
		public boolean apply(Date date)
		{
			return format.format(date).equals(compare);
		}		
	}
	
	public class PostLinkBehaviour extends HtmlBehaviourAdapter
	{
		@Override
		public boolean checkElement(HTMLElement element)
		{
			return element instanceof HTMLLinkElement;
		}

		@Override
		public void performLinkClicked(HtmlRendererContext renderer, HTMLElement element, URL url, String target)
		{
			Post post = HibernateUtil.get(Post.class, "uid", ((HTMLLinkElement)element).getAttribute("href"));
			App.events.firePostSelected(new PostSelectedEvent(this, post));
		}
		
	}
}
